package com.uzai.console.service.log.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.ES.ESResult;
import com.uzai.console.constant.ES.ElasticsearchUtil;
import com.uzai.console.dto.log.useroperationlog.UserOperationLogByManagerSuperQuery;
import com.uzai.console.dto.log.useroperationlog.UserOperationLogQuery;
import com.uzai.console.entity.KefuUser;
import com.uzai.console.entity.Merchant;
import com.uzai.console.entity.es.EsUserOperationLog;
import com.uzai.console.enums.OperationTypeEnum;
import com.uzai.console.enums.SystemModelEnum;
import com.uzai.console.mapper.KefuUserMapper;
import com.uzai.console.mapper.MerchantMapper;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.log.UserOperationLogService;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 系统操作日记查询
 *
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class UserOperationLogServiceImpl implements UserOperationLogService {

    Logger logger = LoggerFactory.getLogger(UserOperationLogServiceImpl.class);

    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private KefuUserMapper kefuUserMapper;
    @Autowired
    private MerchantMapper merchantMapper;

    /**
     * 查询系统操作日记列表-运营商普通登录操作
     *
     * @param userOperationLogQuery
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public Page<EsUserOperationLog> findUserOperationLogList(UserOperationLogQuery userOperationLogQuery) {
        //新建返回到页面的LIST对象
        List<EsUserOperationLog> esUserOperationLogArrayList = new ArrayList<>();

        //执行分页查询对象
        Page<EsUserOperationLog> page = new Page<>();
        userOperationLogQuery.convert(page);

        //ES查询
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        BoolQueryBuilder boolQuery_or_should = QueryBuilders.boolQuery();
        BoolQueryBuilder boolQuery_or_null = QueryBuilders.boolQuery();
        BoolQueryBuilder boolQuery_or_keyword = QueryBuilders.boolQuery();
        //运营商ID
        boolQuery.must(QueryBuilders.termQuery("merId", Tools.getLong(userOperationLogQuery.getMerId())));

        //操作模块
        if(StringUtils.isNotBlank(userOperationLogQuery.getModel())){
            boolQuery.must(QueryBuilders.matchPhraseQuery("model",userOperationLogQuery.getModel()));
        }

        //内容
        if(StringUtils.isNotBlank(userOperationLogQuery.getContent())){
            boolQuery.must(QueryBuilders.matchPhraseQuery("content",userOperationLogQuery.getContent()));
        }

        //操作类型
        if (StringUtils.isNotBlank(userOperationLogQuery.getType())) {
            boolQuery.must(QueryBuilders.termQuery("type", userOperationLogQuery.getType()));
        }

        //账号
        if(StringUtils.isNotBlank(userOperationLogQuery.getAccount())){
            //boolQuery.must(QueryBuilders.termQuery("account",userOperationLogQuery.getAccount()));

            boolQuery_or_keyword.should(QueryBuilders.wildcardQuery("account", "*"+userOperationLogQuery.getAccount() +"*"));
            //支持数字和英文
            boolQuery_or_keyword.should(QueryBuilders.wildcardQuery("account.keyword", "*"+userOperationLogQuery.getAccount() +"*"));
        }

        //查询开始时间
        if (userOperationLogQuery.getQueryStartTime() != null) {
            boolQuery.must(QueryBuilders.rangeQuery("createTime").gte(userOperationLogQuery.getQueryStartTime()));
        }

        //查询结束时间
        if (userOperationLogQuery.getQueryEndTime() != null) {
            boolQuery.must(QueryBuilders.rangeQuery("createTime").lte(userOperationLogQuery.getQueryEndTime()));
        }

        //登录类型不存在或者等于0
        boolQuery_or_should.should(boolQuery_or_null.mustNot(QueryBuilders.existsQuery("loginType")));
        boolQuery_or_should.should(QueryBuilders.termQuery("loginType", 0));

        //高亮字段
        String highlightField = null;
        searchSourceBuilder.query(boolQuery.must(boolQuery_or_should).must(boolQuery_or_keyword));

        logger.info(searchSourceBuilder.toString());

        //排序
        searchSourceBuilder.sort("createTime", SortOrder.DESC);

        logger.info(searchSourceBuilder.toString());

        try {
            ESResult esResult = elasticsearchUtil.searchListData(EsIndexName.UZAI_CONSOLE_USER_OPERATION_LOG, searchSourceBuilder, userOperationLogQuery.getSize(), userOperationLogQuery.getFromIndex(), null, null, highlightField, userOperationLogQuery.getMerId());
            page.setTotal(esResult.getTotalHits());
            List<Map<String, Object>> dataList = esResult.getDataList();
            if (dataList != null && dataList.size() > 0) {
                for (Map<String, Object> dataMp : dataList) {
                    EsUserOperationLog esUserOperationLog = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsUserOperationLog.class);
                    esUserOperationLogArrayList.add(esUserOperationLog);
                    if (StringUtils.isNotBlank(esUserOperationLog.getType())) {
                        OperationTypeEnum operationTypeEnum = OperationTypeEnum.getByKey(esUserOperationLog.getType());
                        if (operationTypeEnum != null) {
                            esUserOperationLog.setType(operationTypeEnum.getDesc());
                        }
                    }
                    if (StringUtils.isNotBlank(esUserOperationLog.getModel())) {
                        SystemModelEnum systemModelEnum = SystemModelEnum.getByKey(esUserOperationLog.getModel());
                        if (systemModelEnum != null) {
                            esUserOperationLog.setModel(systemModelEnum.getDesc());
                        }
                    }

                    //获取账号名称
                    if(StringUtils.isNotBlank(esUserOperationLog.getAccount())){
                        //优先运营商账号
                        String accountName = null;
                        if(Tools.checkPhone(esUserOperationLog.getAccount())){
                            Merchant merchant = merchantMapper.selectByMobile(esUserOperationLog.getAccount());
                            if(merchant != null){
                                accountName = merchant.getName();
                            }
                        }

                        //操作账号还是为空
                        if(StringUtils.isBlank(accountName)){
                            KefuUser kefuUser = kefuUserMapper.selectByUser(esUserOperationLog.getAccount());
                            if(kefuUser != null){
                                accountName = kefuUser.getName();
                            }
                        }

                        if(StringUtils.isNotBlank(accountName)){
                            esUserOperationLog.setAccount(accountName);
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("查询ES账号操作日志出现异常,index=" + EsIndexName.UZAI_CONSOLE_USER_OPERATION_LOG);
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, e.getMessage());
        }

        //返回到页面分页对象
        page.setRecords(esUserOperationLogArrayList);
        //将分页信息复制到返回到页面的分页MO当中
        return page;
    }


    /**
     * 查询账号操作日志列表-查询客服超级账号
     *
     * @param userOperationLogByManagerSuperQuery
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public Page<EsUserOperationLog> findUserOperationLogListByKefuManage(UserOperationLogByManagerSuperQuery userOperationLogByManagerSuperQuery){
        //新建返回到页面的LIST对象
        List<EsUserOperationLog> esUserOperationLogArrayList = new ArrayList<>();

        //执行分页查询对象
        Page<EsUserOperationLog> page = new Page<>();
        userOperationLogByManagerSuperQuery.convert(page);

        //ES查询
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        //操作模块
        if (StringUtils.isNotBlank(userOperationLogByManagerSuperQuery.getModel())) {
            boolQuery.must(QueryBuilders.matchPhraseQuery("model", userOperationLogByManagerSuperQuery.getModel()));
        }

        //操作类型
        if (StringUtils.isNotBlank(userOperationLogByManagerSuperQuery.getType())) {
            boolQuery.must(QueryBuilders.termQuery("type", userOperationLogByManagerSuperQuery.getType()));
        }

        //内容
        if(StringUtils.isNotBlank(userOperationLogByManagerSuperQuery.getContent())){
            boolQuery.must(QueryBuilders.matchPhraseQuery("content",userOperationLogByManagerSuperQuery.getContent()));
        }

        //账号
        if (StringUtils.isNotBlank(userOperationLogByManagerSuperQuery.getAccount())) {
            boolQuery.must(QueryBuilders.termQuery("account", userOperationLogByManagerSuperQuery.getAccount()));
        }

        //查询开始时间
        if (userOperationLogByManagerSuperQuery.getQueryStartTime() != null) {
            boolQuery.must(QueryBuilders.rangeQuery("createTime").gte(userOperationLogByManagerSuperQuery.getQueryStartTime()));
        }

        //查询结束时间
        if (userOperationLogByManagerSuperQuery.getQueryEndTime() != null) {
            boolQuery.must(QueryBuilders.rangeQuery("createTime").lte(userOperationLogByManagerSuperQuery.getQueryEndTime()));
        }

        //客服超级账号
        if (StringUtils.isNotBlank(userOperationLogByManagerSuperQuery.getManagerMobile())) {
            boolQuery.must(QueryBuilders.termQuery("managerMobile", userOperationLogByManagerSuperQuery.getManagerMobile()));
        }

        //登录类型
        boolQuery.must(QueryBuilders.termQuery("loginType", 2)); //客服超级账号登录类型

        //高亮字段
        String highlightField = null;

        searchSourceBuilder.query(boolQuery);

        //排序
        searchSourceBuilder.sort("createTime", SortOrder.DESC);

        try {
            ESResult esResult = elasticsearchUtil.searchListData(EsIndexName.UZAI_CONSOLE_USER_OPERATION_LOG, searchSourceBuilder, userOperationLogByManagerSuperQuery.getSize(), userOperationLogByManagerSuperQuery.getFromIndex(), null, null, highlightField, userOperationLogByManagerSuperQuery.getMerId());
            page.setTotal(esResult.getTotalHits());
            List<Map<String, Object>> dataList = esResult.getDataList();
            if (dataList != null && dataList.size() > 0) {
                for (Map<String, Object> dataMp : dataList) {
                    EsUserOperationLog esUserOperationLog = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsUserOperationLog.class);
                    esUserOperationLogArrayList.add(esUserOperationLog);
                    if (StringUtils.isNotBlank(esUserOperationLog.getType())) {
                        OperationTypeEnum operationTypeEnum = OperationTypeEnum.getByKey(esUserOperationLog.getType());
                        if (operationTypeEnum != null) {
                            esUserOperationLog.setType(operationTypeEnum.getDesc());
                        }
                    }

                    if (StringUtils.isNotBlank(esUserOperationLog.getModel())) {
                        SystemModelEnum systemModelEnum = SystemModelEnum.getByKey(esUserOperationLog.getModel());
                        if (systemModelEnum != null) {
                            esUserOperationLog.setModel(systemModelEnum.getDesc());
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("查询ES账号操作日志出现异常,index=" + EsIndexName.UZAI_CONSOLE_USER_OPERATION_LOG);
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "查询失败");
        }

        //返回到页面分页对象
        page.setRecords(esUserOperationLogArrayList);
        //将分页信息复制到返回到页面的分页MO当中
        return page;
    }


}
